package com.pace.utils;

import com.pace.vo.OrderExcel;
import org.apache.poi.xssf.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

public class Excel {

    /**
     * 将VO写入Excel
     *
     * @param al
     * @return
     */
    public static void toExcel(List<OrderExcel> al, File newExcel, File template) throws RRException {
        try {
            Files.copy(template.toPath(), newExcel.toPath());
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(newExcel));
            XSSFSheet sheet = workbook.getSheetAt(workbook.getSheetIndex("Sheet1"));
            for (int i = 0; i < al.size(); i++) {
                OrderExcel x3OrderVo = al.get(i);
                XSSFRow row = sheet.getRow(i + 1); // 获取指定的行对象，无数据则为空，需要创建
                if (row == null) {
                    row = sheet.createRow(i + 1); // 该行无数据，创建行对象
                }
                row.createCell(0).setCellValue(x3OrderVo.getOrderCode()); // 订单编号
                row.createCell(1).setCellValue(x3OrderVo.getColor());//颜色
                row.createCell(2).setCellValue(x3OrderVo.getTanli());//弹力
                row.createCell(3).setCellValue(x3OrderVo.getSpecificDesc());//规格
                row.createCell(4).setCellValue(x3OrderVo.getMenfu());//门幅
                row.createCell(5).setCellValue(x3OrderVo.getPrice());//单价
//                if (x3OrderVo.getPrice() != null)
//                    row.createCell(5).setCellValue(Double.parseDouble("" + x3OrderVo.getPrice()));//单价
//                wirteDateCell(workbook, row.createCell(6), new Date());//日期
            }
            FileOutputStream fo = new FileOutputStream(newExcel); // 输出到文件
            workbook.write(fo);
        } catch (Exception e) {
            throw new RRException("text2Excel parse error", e);

        }
    }

    /**
     * 写入时间类型
     *
     * @param workbook
     * @param cellWrite
     * @param time
     * @throws ParseException
     */
    private static void wirteDateCell(XSSFWorkbook workbook, XSSFCell cellWrite, Date time) {
        if (time == null) {
            return;
        }
        XSSFCellStyle dateCellStyle = workbook.createCellStyle();
        short df = workbook.createDataFormat().getFormat("yyyy/mm/dd");
        dateCellStyle.setDataFormat(df);
        cellWrite.setCellStyle(dateCellStyle);
        cellWrite.setCellValue(time);
    }

}
